package com.kldy8.kldyw.filmfactory.shootingvenue;

import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.kldy8.kldyw.BaseAppCompatActivity;
import com.kldy8.kldyw.MyWebActivity;
import com.kldy8.kldyw.R;
import com.kldy8.kldyw.filmfactory.bean.City;
import com.kldy8.kldyw.filmfactory.bean.Positions;
import com.kldy8.kldyw.filmfactory.bean.ShootingVenue;
import com.kldy8.kldyw.logre.LoginActivity;
import com.kldy8.kldyw.system.ServerApi;
import com.kldy8.kldyw.system.ServerCallBack;
import com.kldy8.kldyw.system.UrlBuilder;
import com.kldy8.kldyw.tools.widget.view.ExpandTabView;
import com.kldy8.kldyw.tools.widget.view.ViewLeft;
import com.kldy8.kldyw.tools.widget.view.ViewMiddle;
import com.kldy8.kldyw.web.AppWebUrl;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Request;

/**
 * 拍摄场地
 */
public class ShootingVenueActivity extends BaseAppCompatActivity
{
    private XRefreshView refreshView1,refreshView2,refreshView3;

    private List<Positions> positionsList1 = new ArrayList<Positions>();
    private List<City> cityList1 = new ArrayList<City>();

    private List<Positions> positionsList2 = new ArrayList<Positions>();
    private List<City> cityList2 = new ArrayList<City>();

    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private Toolbar toolbar;

    int page1 = 1;
    int position1,city1,price1;
    int page2 = 1;
    int position2,city2,price2;

    private View mFooterView;
    private TextView mFooterTextView;
    private View mFooterLoadingView;

    private LayoutInflater mInflater;
    private List<String> mTitleList = new ArrayList<>();//页卡标题集合
    private View view1, view2;

    ShootingVenueAdapter adapter1,adapter2;
    private List<View> mViewList = new ArrayList<>();//页卡视图集合

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shooting_venue);
        /**
         * 自定义脚部文件
         */
        mFooterView = LayoutInflater.from(this).inflate(R.layout.pulldown_footer, null);
        mFooterTextView = (TextView) mFooterView.findViewById(R.id.pulldown_footer_text);
        mFooterLoadingView = mFooterView.findViewById(R.id.pulldown_footer_loading);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("拍摄场地");//设置主标题
        setSupportActionBar(toolbar);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true); // 决定左上角图标的右侧是否有向左的小箭头, true
        // 有小箭头，并且图标可以点击
        actionBar.setDisplayShowHomeEnabled(false);

        mViewPager = (ViewPager) findViewById(R.id.vp_view);
        mTabLayout = (TabLayout) findViewById(R.id.tabs);

        initViewPage();
        initData();

        Intent intent =  getIntent();
        int item = intent.getIntExtra("item",0);
        mViewPager.setCurrentItem(item);
    }

    private void initData()
    {
        initPersonList(true,page1,position1,city1,price1);
        initCompanyList(true,page2,position2,city2,price2);
    }

    private void initPersonList(final boolean isInit,int page,int position,int city,int price)
    {
        ServerApi.list_out("" + page, "" +position, "" +city, ""+price,new ServerCallBack()
        {
            @Override
            public void onError(Request request, Exception e)
            {
                if (refreshView1!=null)
                {
                    refreshView1.stopRefresh();
                    refreshView1.stopLoadMore();
                }
                Toast.makeText(ShootingVenueActivity.this,getResources().getString(R.string.error_net),Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResponse(String response) throws JSONException
            {
                hiddenFooterView();
                Log.e("......",response.toString());
                ArrayList<ShootingVenue> filmTalentList1 = new ArrayList<ShootingVenue>();

                JSONObject jsonObject = new JSONObject(response);
                if ("0".equals(jsonObject.optString("code")))
                {
                    page1++;
                    JSONObject objectData = jsonObject.optJSONObject("data");
                    JSONArray objectCatelist = objectData.optJSONArray("cate_list");
                    JSONArray objectCities = objectData.optJSONArray("cities");
                    JSONArray objectList = objectData.optJSONArray("list");

                    if (isInit == true)
                    {
                        page1 = 2;
                    }

                    if (null != objectCatelist && objectCatelist.length()>0)
                    {
                        for (int i = 0; i < objectCatelist.length(); i++) {
                            JSONObject objectPosition = objectCatelist.optJSONObject(i);
                            Positions positions = Positions.resolution(objectPosition);
                            if (positions != null) {
                                positionsList1.add(positions);
                            }
                        }

                    }

                    if (null != objectCities && objectCities.length()>0) {

                        for (int i = 0; i < objectCities.length(); i++) {
                            JSONObject objectCity = objectCities.optJSONObject(i);
                            City city = new City();
                            city.resolution(objectCity);
                            cityList1.add(city);
                        }
                    }

                    if (null != objectList && objectList.length()>0)
                    {
                        for (int i = 0; i < objectList.length(); i++) {
                            JSONObject object = objectList.optJSONObject(i);
                            ShootingVenue filmTalent = ShootingVenue.resolution(object);

                            if (filmTalent != null)
                            {
                                filmTalentList1.add(filmTalent);
                            }
                        }
                    }
                    adapter1.replaceOrAdd(isInit,filmTalentList1);
                    adapter1.notifyDataSetChanged();

                    initExpandView(1,positionsList1,cityList1);
                    initExpandVaule(1);
                    initExpandListener(1);
                }
                else  if ("10004".equals(jsonObject.optString("code")))
                {
                    Intent intent2 = new Intent();
                    intent2.setClass(ShootingVenueActivity.this, LoginActivity.class);
                    startActivity(intent2);
                    ShootingVenueActivity.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
                }
                if (refreshView1!=null)
                {
                    refreshView1.stopRefresh();
                    refreshView1.stopLoadMore();
                }
            }
        });
    }

    private void initCompanyList(final boolean isInit, int page, int position, final int city, int price)
    {
        Log.e("page",""+page);
        ServerApi.list_in("" + page, "" +position, "" +city, ""+price, new ServerCallBack()
        {
            @Override
            public void onError(Request request, Exception e)
            {
                if (refreshView2!=null)
                {
                    refreshView2.stopRefresh();
                    refreshView2.stopLoadMore();
                }
                Toast.makeText(ShootingVenueActivity.this,getResources().getString(R.string.error_net),Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResponse(String response) throws JSONException
            {
                ArrayList<ShootingVenue> filmTalentList2 = new ArrayList<ShootingVenue>();

                Log.e("......",response.toString());
                JSONObject jsonObject = new JSONObject(response);

                if ("0".equals(jsonObject.optString("code")))
                {
                    page2++;

                    if (isInit == true)
                    {
                        page2 = 2;
                    }
                    JSONObject objectData = jsonObject.optJSONObject("data");
                    JSONArray objectCatelist = objectData.optJSONArray("cate_list");
                    JSONArray objectCities = objectData.optJSONArray("cities");
                    JSONArray objectList = objectData.optJSONArray("list");

                    if (null != objectCatelist && objectCatelist.length()>0)
                    {
                        for (int i = 0;i<objectCatelist.length();i++)
                        {
                            JSONObject objectPosition = objectCatelist.optJSONObject(i);
                            Positions positions = Positions.resolution(objectPosition);
                            if (positions != null)
                            {
                                positionsList2.add(positions);
                            }
                        }
                    }

                    if (null != objectCities && objectCities.length()>0)
                    {
                        for (int i = 0; i < objectCities.length(); i++)
                        {
                            JSONObject objectCity = objectCities.optJSONObject(i);
                            City city = new City();
                            city.resolution(objectCity);
                            cityList2.add(city);
                        }
                    }

                    if (null != objectList && objectList.length()>0)
                    {
                        for (int i = 0; i < objectList.length(); i++)
                        {
                            JSONObject object = objectList.optJSONObject(i);
                            ShootingVenue filmTalent = ShootingVenue.resolution(object);
                            if (filmTalent != null)
                            {
                                filmTalentList2.add(filmTalent);
                            }
                        }
                    }
                    adapter2.replaceOrAdd(isInit,filmTalentList2);
                    adapter2.notifyDataSetChanged();


                    initExpandView(2,positionsList2,cityList2);
                    initExpandVaule(2);
                    initExpandListener(2);

                }
                else  if ("10004".equals(jsonObject.optString("code")))
                {
                    Intent intent2 = new Intent();
                    intent2.setClass(ShootingVenueActivity.this, LoginActivity.class);
                    startActivity(intent2);
                    ShootingVenueActivity.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
                }


                if (refreshView2!=null)
                {
                    refreshView2.stopRefresh();
                    refreshView2.stopLoadMore();
                }
            }
        });
    }

    private void initListView(View view)
    {

        ListView list_view = (ListView) view.findViewById(R.id.list_view);

        if (view == view1)
        {
            adapter1 = new ShootingVenueAdapter(this, new ArrayList<ShootingVenue>(),0);
            list_view.setAdapter(adapter1);

            refreshView1 = (XRefreshView) view.findViewById(R.id.xrefreshview);
            refreshView1.setPullLoadEnable(true);

            //设置刷新完成以后，headerview固定的时间
            refreshView1.setPinnedTime(1000);
            refreshView1.setPullLoadEnable(true);
            refreshView1.setMoveForHorizontal(true);
            refreshView1.setAutoLoadMore(true);
            refreshView1.setEmptyView(R.layout.layout_emptyview);
            refreshView1.getEmptyView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refreshView1.startRefresh();
                }
            });

            refreshView1.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

                @Override
                public void onRefresh() {
                    requestPeopleData();
                }

                @Override
                public void onLoadMore(boolean isSilence) {
                    morePeopleData();
                }
            });
        }
        else
        {
            adapter2 = new ShootingVenueAdapter(this, new ArrayList<ShootingVenue>(),1);
            list_view.setAdapter(adapter2);
            refreshView2 = (XRefreshView) view.findViewById(R.id.xrefreshview);
            refreshView2.setPullLoadEnable(true);

            //设置刷新完成以后，headerview固定的时间
            refreshView2.setPinnedTime(1000);
            refreshView2.setPullLoadEnable(true);
            refreshView2.setMoveForHorizontal(true);
            refreshView2.setAutoLoadMore(true);
            refreshView2.setEmptyView(R.layout.layout_emptyview);
            refreshView2.getEmptyView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refreshView2.startRefresh();
                }
            });

            refreshView2.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

                @Override
                public void onRefresh() {
                    requestComData();
                }

                @Override
                public void onLoadMore(boolean isSilence) {
                    moreComData();
                }
            });
        }
    }


    //刷新人才求职数据
    public void requestPeopleData()
    {
        initPersonList(true,1,position1,city1,price1);
    }
    //添加人才求职数据
    public void morePeopleData()
    {
        initPersonList(false,page1,position1,city1,price1);
    }


    //刷新人才招募数据
    public void requestComData()
    {
        initCompanyList(true,1,position2,city2,price2);
    }
    //添加人才招募数据
    public void moreComData()
    {
        initCompanyList(false,page2,position2,city2,price2);
    }

    private void initViewPage()
    {
        mInflater = LayoutInflater.from(this);
        view1 = mInflater.inflate(R.layout.view_film_talent, null);
        expandTabView1 = (ExpandTabView) view1.findViewById(R.id.expandtab_view);
        initListView(view1);

        view2 = mInflater.inflate(R.layout.view_film_talent, null);
        expandTabView2 = (ExpandTabView) view2.findViewById(R.id.expandtab_view);
        initListView(view2);


        //添加页卡视图
        mViewList.add(view1);
        mViewList.add(view2);

        //添加页卡标题
        mTitleList.add("场地出租");
        mTitleList.add("场地求租");

        mTabLayout.setTabMode(TabLayout.MODE_FIXED);//设置tab模式，当前为系统默认模式
        mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(0)));//添加tab选项卡
        mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(1)));

        MyPagerAdapter mAdapter = new MyPagerAdapter(mViewList);
        mViewPager.setAdapter(mAdapter);//给ViewPager设置适配器
        mTabLayout.setupWithViewPager(mViewPager);//将TabLayout和ViewPager关联起来。
        mTabLayout.setTabsFromPagerAdapter(mAdapter);//给Tabs设置适配器
    }


    //ViewPager适配器
    class MyPagerAdapter extends PagerAdapter
    {
        private List<View> mViewList;

        public MyPagerAdapter(List<View> mViewList)
        {
            this.mViewList = mViewList;
        }

        @Override
        public int getCount()
        {
            return mViewList.size();//页卡数
        }

        @Override
        public boolean isViewFromObject(View view, Object object)
        {
            return view == object;//官方推荐写法
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            container.addView(mViewList.get(position));//添加页卡
            return mViewList.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object)
        {
            container.removeView(mViewList.get(position));//删除页卡
        }

        @Override
        public CharSequence getPageTitle(int position)
        {
            return mTitleList.get(position);//页卡标题
        }

    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        if (item.getItemId() == android.R.id.home)
        {
            finish();
            return true ;
        }

        if (item.getItemId() == R.id.action_search)
        {
            Intent intent = new Intent();
            String resultUrl = AppWebUrl.createUrl(UrlBuilder.URL_BASE_API+"/search/search_make_result?t_type=4&keyword=");
            intent.putExtra("url",resultUrl);
            intent.setClass(this, MyWebActivity.class);
            startActivityRightToLeft(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_notbtn, menu);
//        MenuItem menuItem = menu.findItem(R.id.action_search);//在菜单中找到对应控件的item
//        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
//        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
//        {
//
//            public boolean onQueryTextSubmit(String query)
//            {
//                Log.e("tag",query);
//                Intent intent=new Intent(ShootingVenueActivity.this,SearchActivity.class);  //方法1
//                Bundle bundle=new Bundle();
//                String[] languages=getResources().getStringArray(R.array.search_array);
//
//                bundle.putString(SearchActivity.TAG_ITEM,languages[0]);
//                bundle.putString(SearchActivity.TAG_KEY, query);
//                intent.putExtras(bundle);
//                startActivity(intent);
//                overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
//
//                return true;
//            }
//
//            public boolean onQueryTextChange(String newText)
//            {
//                return true;
//            }
//        });



//        Log.d("Tag", "menu create");
//        MenuItemCompat.setOnActionExpandListener(menuItem, new MenuItemCompat.OnActionExpandListener() {//设置打开关闭动作监听
//            @Override
//            public boolean onMenuItemActionExpand(MenuItem item)
//            {
//                Toast.makeText(ShootingVenueActivity.this, "onExpand", Toast.LENGTH_LONG).show();
//                return true;
//            }
//
//            @Override
//            public boolean onMenuItemActionCollapse(MenuItem item) {
//                Toast.makeText(ShootingVenueActivity.this, "Collapse", Toast.LENGTH_LONG).show();
//                return true;
//            }
//        });
        return super.onCreateOptionsMenu(menu);
    }

    private ExpandTabView expandTabView1;
    private ExpandTabView expandTabView2;

    private ArrayList<View> mViewArray1;
    private ArrayList<View> mViewArray2 ;

    private ViewLeft viewLeft,viewLeft2;
    private ViewMiddle viewMiddle,viewMiddle2;
    private ViewLeft viewRight,viewRight2;

    /**
     *
     * @param type 1为第一页 2为第二页
     * @param positionses
     * @param cities
     */
    private void initExpandView(int type,List<Positions> positionses,List<City> cities)
    {
        if (type == 1)
        {
            viewLeft = new ViewLeft(this, positionses);
            viewMiddle = new ViewMiddle(this, cities);
            viewRight = new ViewLeft(this);
        }
        else if(type == 2)
        {
            viewLeft2 = new ViewLeft(this, positionses);
            viewMiddle2 = new ViewMiddle(this, cities);
            viewRight2 = new ViewLeft(this);
        }
    }

    /**
     *
     * @param type 1为第一页 2为第二页
     */
    private void initExpandVaule(int type)
    {
        if (type == 1)
        {
            if (expandTabView1!=null)
            {
                expandTabView1.removeAllViews();
            }
            mViewArray1 = new ArrayList<View>();
            mViewArray1.add(viewLeft);
            mViewArray1.add(viewRight);
            mViewArray1.add(viewMiddle);
            ArrayList<String> mTextArray = new ArrayList<String>();
            mTextArray.add("类型");
            mTextArray.add("价格");
            mTextArray.add("地区");
            expandTabView1.setValue(mTextArray, mViewArray1);
        }
        else if(type == 2)
        {
            if (expandTabView2!=null)
            {
                expandTabView2.removeAllViews();
            }
            mViewArray2 = new ArrayList<View>();
            mViewArray2.add(viewLeft2);
            mViewArray2.add(viewRight2);
            mViewArray2.add(viewMiddle2);
            ArrayList<String> mTextArray = new ArrayList<String>();
            mTextArray.add("类型");
            mTextArray.add("价格");
            mTextArray.add("地区");
            expandTabView2.setValue(mTextArray, mViewArray2);
        }

//		expandTabView.setTitle(viewLeft.getShowText(), 0);
//		expandTabView.setTitle(viewMiddle.getShowText(), 1);
//		expandTabView.setTitle(viewRight.getShowText(), 2);

    }

    /**
     *
     * @param type 1为第一页 2为第二页
     */
    private void initExpandListener(int type)
    {
        if (type == 1)
        {
            viewLeft.setOnSelectListener(new ViewLeft.OnSelectListener()
            {
                @Override
                public void getValue(String distance, String showText)
                {
                    onRefresh(expandTabView1,viewLeft, showText);
                }

                @Override
                public void getValue(Positions positions, String showText)
                {
                    if (positions != null)
                    {
                        position1 = positions.id;
                    }
                }
            });

            viewMiddle.setOnSelectListener(new ViewMiddle.OnSelectListener()
            {

                @Override
                public void getValue(String showText)
                {
                    onRefresh(expandTabView1,viewMiddle, showText);
                }

                @Override
                public void getValue(City.Son son)
                {
                    if (son != null)
                    {
                        city1 = son.id;
                    }
                }
            });

            viewRight.setOnSelectListener(new ViewLeft.OnSelectListener()
            {
                @Override
                public void getValue(String distance, String showText)
                {
                    onRefresh(expandTabView1,viewRight, showText);
                }

                @Override
                public void getValue(Positions positions, String showText)
                {
                    if (positions != null)
                    {
                        position1 = positions.id;
                    }
                }
            });
        }
        else if(type == 2)
        {
            viewLeft2.setOnSelectListener(new ViewLeft.OnSelectListener()
            {
                @Override
                public void getValue(String distance, String showText)
                {
                    onRefresh(expandTabView2,viewLeft2, showText);
                }

                @Override
                public void getValue(Positions positions, String showText)
                {
                    if (positions != null)
                    {
                        position2 = positions.id;
                    }
                }
            });

            viewMiddle2.setOnSelectListener(new ViewMiddle.OnSelectListener()
            {

                @Override
                public void getValue(String showText)
                {
                    onRefresh(expandTabView2,viewMiddle2, showText);
                }

                @Override
                public void getValue(City.Son son)
                {
                    if (son != null)
                    {
                        city2 = son.id;
                    }
                }
            });

            viewRight2.setOnSelectListener(new ViewLeft.OnSelectListener()
            {
                @Override
                public void getValue(String distance, String showText)
                {
                    onRefresh(expandTabView2,viewRight2, showText);
                }

                @Override
                public void getValue(Positions positions, String showText)
                {
                    if (positions != null)
                    {
                        position2 = positions.id;
                    }
                }
            });
        }
    }

    private void onRefresh(ExpandTabView expandTabView,View view, String showText)
    {
        expandTabView.onPressBack();
        int position = getPositon(expandTabView,view);
        if (position >= 0 && !expandTabView.getTitle(position).equals(showText))
        {
            expandTabView.setTitle(showText, position);
        }
        Toast.makeText(this, showText, Toast.LENGTH_SHORT).show();
    }

    private int getPositon(ExpandTabView expandTabView,View tView)
    {
        if (expandTabView == expandTabView1)
        {
            for (int i = 0; i < mViewArray1.size(); i++) {
                if (mViewArray1.get(i) == tView) {
                    return i;
                }
            }
        }
        else if (expandTabView == expandTabView2)
        {
            for (int i = 0; i < mViewArray2.size(); i++)
            {
                if (mViewArray2.get(i) == tView)
                {
                    return i;
                }
            }
        }
        return -1;
    }




    private void hiddenFooterView()
    {
        mFooterLoadingView.setVisibility(View.GONE);
        mFooterTextView.setText("更多");
        mFooterLoadingView.setVisibility(View.GONE);
    }
    private void showFooterView()
    {
        mFooterLoadingView.setVisibility(View.VISIBLE);
        mFooterTextView.setText("正在加载.....");
        mFooterLoadingView.setVisibility(View.VISIBLE);
    }
}
